import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import dayjs from 'dayjs';
import { readFileSync, writeFileSync } from 'node:fs';
import { URL, fileURLToPath } from 'node:url';
import path from 'path';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { defineConfig, loadEnv } from 'vite';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import vueDevTools from 'vite-plugin-vue-devtools';

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  console.log(mode);

  const {
    VITE_BASE_TITLE,
    VITE_BASE_API_URL,
    VITE_TOKEN_KEY,
    VITE_DEFAULT_PASS,
    VITE_DATE_FORMAT,
    VITE_TABS_MAX_LENGTH,
    VITE_WS_HOST,
  } = loadEnv(mode, process.cwd());

  const esbuild = {};

  if (mode !== 'development') {
    Object.assign(esbuild, {
      drop: ['console', 'debugger'],
    });
  }

  const VITE_WDM_THEME = process.env.VITE_WDM_THEME || 'by';
  console.log('VITE_WDM_THEME:', VITE_WDM_THEME);

  return {
    define: {
      VITE_BASE_TITLE: JSON.stringify(VITE_BASE_TITLE),
      VITE_BASE_API_URL: JSON.stringify(VITE_BASE_API_URL),
      VITE_TOKEN_KEY: JSON.stringify(VITE_TOKEN_KEY),
      VITE_DEFAULT_PASS: JSON.stringify(VITE_DEFAULT_PASS),
      VITE_DATE_FORMAT: JSON.stringify(VITE_DATE_FORMAT),
      VITE_TABS_MAX_LENGTH: JSON.stringify(VITE_TABS_MAX_LENGTH),
      VITE_WS_HOST: JSON.stringify(VITE_WS_HOST),
      NODE_ENV: JSON.stringify(mode),
      VITE_WDM_THEME: JSON.stringify(VITE_WDM_THEME),
    },
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      // Components({
      //   resolvers: [AntDesignVueResolver()],
      // }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
        customDomId: '__svg__icons__dom__',
      }),
      {
        name: 'custom-html',
        configureServer: (server) => {
          server.middlewares.use((req, res, next) => {
            const url = req.url;
            const isMobile = url?.startsWith('/h5') && !url.includes('.');
            if (isMobile) {
              res.end(`
                <!doctype html>
                <html lang="en">
                  <head>
                    <meta charset="UTF-8" />
                    <link rel="icon" href="/favicon.ico" />
                    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
                    <title>${VITE_BASE_TITLE}</title>
                  </head>
                  <body>
                    <div id="app"></div>
                    <script type="module" src="/h5/main.ts"></script>
                  </body>
                </html>
              `);
              return;
            }
            next();
          });
        },
      },
      {
        name: 'version-plugin',
        buildEnd() {
          const version = dayjs().valueOf();
          writeFileSync('./public/version.json', JSON.stringify({ version }));
          console.log(`Generated version.json with version: ${version}`);
        },
      },
      {
        name: 'wdm-theme-plugin',
        transform(code, id) {
          if (id.endsWith('.ts')) {
            return code.replace(/VITE_WDM_THEME/g, VITE_WDM_THEME);
          }
        },
      },
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@5': fileURLToPath(new URL('./h5', import.meta.url)),
      },
    },
    build: {
      rollupOptions: {
        input: {
          main: path.resolve(__dirname, 'index.html'),
        },
      },
    },
    // 打包去除console、debugger
    esbuild,
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler', // 或 "modern"，"legacy"
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 9622,
      open: true,
      watch: {
        usePolling: true,
      },
      proxy: {
        '^/api': {
          target: 'http://wdm.dev.boeyo.com/',
          // target: 'http://192.168.60.99:9603/', // 李童童本地
          // target: 'http://192.168.22.9:9603/',
          changeOrigin: true,
          ws: true,
        },
      },
      warmup: {
        // 请注意，只应该预热频繁使用的文件，以免在启动时过载 Vite 开发服务器
        // 可以通过运行 npx vite --debug transform 并检查日志来找到频繁使用的文件
        clientFiles: ['./index.html', './src/{components,api}/*'],
      },
    },
  };
});
